/**
 * 玩家商店 - Pinia Store
 * 管理玩家状态的集中式存储
 */
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { Player, PlayerStats, PlayerPreferences } from '@/entities/Player';
import { ServiceManager } from '@/services';

export const usePlayerStore = defineStore('player', () => {
  // 状态
  const currentPlayer = ref<Player | null>(null);
  const players = ref<Player[]>([]);
  const isLoading = ref(false);
  const error = ref<string | null>(null);

  // 计算属性
  const isLoggedIn = computed(() => currentPlayer.value !== null);
  const playerCount = computed(() => players.value.length);
  
  // 获取当前玩家统计
  const currentPlayerStats = computed(() => {
    return currentPlayer.value?.stats || null;
  });

  // 获取当前玩家偏好
  const currentPlayerPreferences = computed(() => {
    return currentPlayer.value?.preferences || null;
  });

  // 获取玩家等级进度
  const levelProgress = computed(() => {
    return currentPlayer.value?.levelProgress || 0;
  });

  // 获取玩家好友数量
  const friendCount = computed(() => {
    return currentPlayer.value?.friendList.length || 0;
  });

  // 获取玩家成就数量
  const achievementCount = computed(() => {
    return currentPlayer.value?.achievementList.length || 0;
  });

  // 获取在线玩家
  const onlinePlayers = computed(() => {
    return players.value.filter(p => p.isOnline);
  });

  // 私有方法
  const setError = (message: string) => {
    error.value = message;
    setTimeout(() => {
      error.value = null;
    }, 5000);
  };

  // 玩家管理操作
  const createPlayer = async (playerData: Partial<Player>) => {
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const newPlayer = await playerManager.createPlayer(playerData);
      players.value.push(newPlayer);
      return newPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '创建玩家失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const login = async (username: string, password: string) => {
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const player = playerManager.findPlayerByUsername(username);
      
      if (!player) {
        throw new Error('玩家不存在');
      }

      // 这里应该添加密码验证逻辑
      // 简化处理，直接登录
      currentPlayer.value = player;
      playerManager.setCurrentPlayer(player);
      
      // 更新最后活跃时间
      await playerManager.updateLastActive(player.id);
      
      return player;
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const logout = async () => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      await playerManager.logoutPlayer(currentPlayer.value.id);
      currentPlayer.value = null;
    } catch (err) {
      setError(err instanceof Error ? err.message : '登出失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const updatePlayer = async (updates: Partial<Player>) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.updatePlayer(currentPlayer.value.id, updates);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '更新玩家信息失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const updatePlayerStats = async (statUpdates: Partial<PlayerStats>) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.updatePlayerStats(currentPlayer.value.id, statUpdates);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '更新玩家统计失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const updatePlayerPreferences = async (preferenceUpdates: Partial<PlayerPreferences>) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.updatePlayerPreferences(currentPlayer.value.id, preferenceUpdates);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '更新玩家偏好失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const addExperience = async (experience: number) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.addExperience(currentPlayer.value.id, experience);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '添加经验失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const addCoins = async (coins: number) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.addCoins(currentPlayer.value.id, coins);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '添加金币失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const addGems = async (gems: number) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.addGems(currentPlayer.value.id, gems);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '添加宝石失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const addFriend = async (friendId: string) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.addFriend(currentPlayer.value.id, friendId);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '添加好友失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const removeFriend = async (friendId: string) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.removeFriend(currentPlayer.value.id, friendId);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '移除好友失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const addAchievement = async (achievementId: string) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.addAchievement(currentPlayer.value.id, achievementId);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '添加成就失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const startCase = async (caseId: string) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.startCase(currentPlayer.value.id, caseId);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '开始案件失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const completeCase = async (caseId: string, score: number, timeSpent: number) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.completeCase(currentPlayer.value.id, caseId, score, timeSpent);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '完成案件失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const failCase = async (caseId: string) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.failCase(currentPlayer.value.id, caseId);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '案件失败处理失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const favoriteCase = async (caseId: string) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.favoriteCase(currentPlayer.value.id, caseId);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '收藏案件失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const unfavoriteCase = async (caseId: string) => {
    if (!currentPlayer.value) return;
    
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const updatedPlayer = await playerManager.unfavoriteCase(currentPlayer.value.id, caseId);
      if (updatedPlayer) {
        currentPlayer.value = updatedPlayer;
      }
      return updatedPlayer;
    } catch (err) {
      setError(err instanceof Error ? err.message : '取消收藏案件失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  // 加载所有玩家
  const loadPlayers = async () => {
    isLoading.value = true;
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const allPlayers = playerManager.getAllPlayers();
      players.value = allPlayers;
      return allPlayers;
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载玩家列表失败');
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  const getLeaderboard = async (limit: number = 10, sortBy: keyof PlayerStats = 'totalScore') => {
    try {
      const playerManager = ServiceManager.getInstance().getPlayerManager();
      const leaderboard = playerManager.getLeaderboard(limit, sortBy);
      return leaderboard;
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取排行榜失败');
      throw err;
    }
  };

  // 重置状态
  const reset = () => {
    currentPlayer.value = null;
    players.value = [];
    isLoading.value = false;
    error.value = null;
  };

  return {
    // 状态
    currentPlayer,
    players,
    isLoading,
    error,
    
    // 计算属性
    isLoggedIn,
    playerCount,
    currentPlayerStats,
    currentPlayerPreferences,
    levelProgress,
    friendCount,
    achievementCount,
    onlinePlayers,
    
    // 方法
    createPlayer,
    login,
    logout,
    updatePlayer,
    updatePlayerStats,
    updatePlayerPreferences,
    addExperience,
    addCoins,
    addGems,
    addFriend,
    removeFriend,
    addAchievement,
    startCase,
    completeCase,
    failCase,
    favoriteCase,
    unfavoriteCase,
    loadPlayers,
    getLeaderboard,
    reset
  };
});